package com.lcf.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.lcf.framework.utils.UserUtils;
import com.lcf.system.dao.UserAddressDao;
import com.lcf.system.dto.UserAddressDTO;
import com.lcf.system.entity.UserAddress;
import com.lcf.system.service.UserAddressService;
import com.lcf.system.vo.UserAddressVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * 收货地址(UserAddress)表服务实现类
 *
 * @author lcf
 * @since 2025-05-02 11:55:04
 */
@Service("userAddressService")
public class UserAddressServiceImpl extends ServiceImpl<UserAddressDao, UserAddress> implements UserAddressService {
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insert(UserAddressDTO dto) {
        UserAddress userAddress = BeanUtil.copyProperties(dto, UserAddress.class);
        userAddress.setUserId(UserUtils.getUserId());

        if (Objects.equals(dto.getIsDefault(), 1)) {
            Db.lambdaUpdate(UserAddress.class)
                    .eq(UserAddress::getUserId, UserUtils.getUserId())
                    .set(UserAddress::getIsDefault, 0)
                    .update();
        }

        return userAddress.insert();
    }

    @Override
    public boolean update(Long id, UserAddressDTO dto) {
        UserAddress userAddress = BeanUtil.copyProperties(dto, UserAddress.class);
        userAddress.setId(id);

        if (Objects.equals(dto.getIsDefault(), 1)) {
            Db.lambdaUpdate(UserAddress.class)
                    .eq(UserAddress::getUserId, UserUtils.getUserId())
                    .set(UserAddress::getIsDefault, 0)
                    .update();
        }

        return userAddress.updateById();
    }

    @Override
    public boolean delete(Long id) {
        return removeById(id);
    }

    @Override
    public UserAddressVO query(Long id) {
        UserAddress userAddress = getById(id);
        return BeanUtil.copyProperties(userAddress, UserAddressVO.class);
    }

    @Override
    public List<UserAddressVO> myList() {
        List<UserAddress> list = Db.lambdaQuery(UserAddress.class)
                .eq(UserAddress::getUserId, UserUtils.getUserId())
                .list();

        return BeanUtil.copyToList(list, UserAddressVO.class);
    }
}

